<!doctype html>
<html class="theme-next use-motion theme-next-mist">
<head>
  
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

  <meta name="google-site-verification" content="K8DCBviaoTBKVs28YBB7IBIbospQ9RVlgSh81RYMUhY" />


  <meta name="baidu-site-verification" content="tXr3ZTm3Hx" />



  <link rel="stylesheet" type="text/css" href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5"/>


<link rel="stylesheet" type="text/css" href="/css/main.css?v=0.4.5.1"/>

  <meta name="description" content="xgfe's blog. 鲜果前端的技术博客，鲜果前端研发部官方博客。前端基础技术研究：html, html5, javascript, css, css3；前端框架研究：angularJs, react, react native." />


  <meta name="keywords" content="angularjs,form," />


  <link rel="alternate" target="_blank" href="/atom.xml" title="xgfe" type="application/atom+xml" />


  <link rel="shorticon icon" type="image/x-icon" href="http://p0.meituan.net/xgfe/2db359f56ce13be30dedef160e0e57ce16958.ico?v=0.4.5.1" />

<meta name="description" content="长文慎入 译自：Taming Forms in AngularJS 1.3 在AngularJs 1.3中form表单得到了大幅度的优化，解决了大量的与浏览器原生HTML5验证的bug，同时增加了诸如“验证器管道”（validators pipeline）和“异步验证”（asynchronous validations）等新特性。辅以“嵌套表单”（nested form）和新的消息提示模块（ngM">
<meta name="keywords" content="angularjs,form">
<meta property="og:type" content="article">
<meta property="og:title" content="学习如何使用AngularJs 1.3中的新form表单特性">
<meta property="og:url" content="http://xgfe.github.io/2015/11/30/felix/forms-in-angularjs-1.3/index.html">
<meta property="og:site_name" content="xgfe">
<meta property="og:description" content="长文慎入 译自：Taming Forms in AngularJS 1.3 在AngularJs 1.3中form表单得到了大幅度的优化，解决了大量的与浏览器原生HTML5验证的bug，同时增加了诸如“验证器管道”（validators pipeline）和“异步验证”（asynchronous validations）等新特性。辅以“嵌套表单”（nested form）和新的消息提示模块（ngM">
<meta property="og:image" content="http://www.yearofmoo.com/images/site/mookins/2.png">
<meta property="og:image" content="http://www.yearofmoo.com/images/site/mookins/20.png">
<meta property="og:updated_time" content="2017-04-12T08:03:36.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="学习如何使用AngularJs 1.3中的新form表单特性">
<meta name="twitter:description" content="长文慎入 译自：Taming Forms in AngularJS 1.3 在AngularJs 1.3中form表单得到了大幅度的优化，解决了大量的与浏览器原生HTML5验证的bug，同时增加了诸如“验证器管道”（validators pipeline）和“异步验证”（asynchronous validations）等新特性。辅以“嵌套表单”（nested form）和新的消息提示模块（ngM">
<meta name="twitter:image" content="http://www.yearofmoo.com/images/site/mookins/2.png">


<script type="text/javascript" id="hexo.configuration">
  var CONFIG = {
    scheme: 'Mist',
    sidebar: 'post'
  };
</script>

  <title> 学习如何使用AngularJs 1.3中的新form表单特性 | xgfe </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  <div style="position: fixed; top: -9999px; left: -9999px;">
    <img src="http://p0.meituan.net/xgfe/082a9624ba5ae8602150a2d43968463e49348.png" alt="xgfe"/>
  </div>
  <!--[if lte IE 8]>
  <div style=' clear: both; height: 59px; padding:0 0 0 15px; position: relative;margin:0 auto;'>
    <a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode">
      <img src="http://7u2nvr.com1.z0.glb.clouddn.com/picouterie.jpg" border="0" height="42" width="820"
           alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today or use other browser ,like chrome firefox safari."
           style='margin-left:auto;margin-right:auto;display: block;'/>
    </a>
  </div>
<![endif]-->
  

  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?3601d4483819a5ab6ddabb0b6422a328";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



  <div class="container one-column page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><h1 class="site-meta">
  <span class="logo-line-before"><i></i></span>
  <a href="/" class="brand" rel="start">
      <span class="logo">
        <i class="icon-next-logo"></i>
      </span>
      <span class="site-title">xgfe</span>
  </a>
  <span class="logo-line-after"><i></i></span>
</h1>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  
  

  
    <ul id="menu" class="menu menu-left">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon icon-next-home"></i> <br />
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            <i class="menu-item-icon icon-next-archives"></i> <br />
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            <i class="menu-item-icon icon-next-tags"></i> <br />
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-join">
          <a href="/join" rel="section">
            <i class="menu-item-icon icon-next-join"></i> <br />
            加入我们
          </a>
        </li>
      
      <!-- slide-links added by felix -->
      <li class="menu-item menu-item-slides" style="opacity: 1; transform: translateY(0px);">
        <a href="http://xgfe.github.io/Basics/" target="_blank" rel="section">
          <i class="menu-item-icon icon-next-slides"></i> <br>
          Basics
        </a>
      </li>
      <li class="menu-item menu-item-slides" style="opacity: 1; transform: translateY(0px);">
        <a href="https://slides.com/xgfe" target="_blank" rel="section">
          <i class="menu-item-icon icon-next-slides"></i> <br>
          Slides
        </a>
      </li>

      
      
    </ul>
  

  
    <div class="site-search">
      

    </div>
  

    <div class="site-search">
      <form class="site-search-form" id="gg-form" action="https://www.google.com/webhp" >
        <input type="text" name="q" id="gg-search-input" class="menu-search-input">
      </form>
    </div>
</nav>
 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div id="content" class="content"> 

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <header class="post-header">

      
      
        <h1 class="post-title" itemprop="name headline">
          
          
            
              学习如何使用AngularJs 1.3中的新form表单特性
            
          
        </h1>
      

      <div class="post-meta">
        <span class="post-time">
          发表于
          <time itemprop="dateCreated" datetime="2015-11-30T22:34:00+08:00" content="2015-11-30">
            2015-11-30
          </time>
        </span>

        
          <span class="post-category" >
            &nbsp; | &nbsp; 作者
            
              <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                <a href="/categories/felix/" itemprop="url" rel="index">
                  <span itemprop="name">felix</span>
                </a>
              </span>

              
              

            
          </span>
        

        
          
        

        <!-- tags 挪动位置 -->
        
          <span class="post-tags">
            &nbsp; | &nbsp;
            
              <a href="/tags/angularjs/" rel="tag"><i class="icon-next-tags"></i>angularjs</a>
            
              <a href="/tags/form/" rel="tag"><i class="icon-next-tags"></i>form</a>
            
          </span>
        
      </div>
    </header>

    <div class="post-body">

      
      

      
        <span itemprop="articleBody"><p><strong>长文慎入</strong></p>
<p>译自：<a href="http://www.yearofmoo.com/2014/09/taming-forms-in-angularjs-1-3.html" target="_blank" rel="external">Taming Forms in AngularJS 1.3</a></p>
<p>在AngularJs 1.3中form表单得到了大幅度的优化，解决了大量的与浏览器原生HTML5验证的bug，同时增加了诸如“验证器管道”（validators pipeline）和“异步验证”（asynchronous validations）等新特性。辅以“嵌套表单”（nested form）和新的消息提示模块（ngMessages），1.3中的form表单变得空前强大。</p>
<a id="more"></a>
<p><img src="http://www.yearofmoo.com/images/site/mookins/2.png" alt="盗图1"></p>
<p>下面让我们一起来领略这些惊人的表单新特性吧。</p>
<p><strong>最近更新</strong></p>
<p>本文首次发表于2014年9月2日，最近修改于2014年9月4日。  </p>
<p><strong>目录</strong></p>
<p><a href="#angular-form">1、Angular中的表单验证</a><br><a href="#video-github">2、演讲视频，Github仓库和演示应用</a><br><a href="#basics">3、基础知识</a><br><a href="#html5-validation-errors">4、HTML5验证器和解析错误</a><br><a href="#validators-pipeline">5、验证器管道($validators pipeline)</a><br><a href="#async-validators">6、通过异步验证器实现异步验证</a><br><a href="#errors-rendering">7、错误消息渲染</a><br><a href="#ng-model-options">8、控制何时更新数据模型(model)</a><br><a href="#dynamic-forms">9、动态生成表单元素</a><br><a href="#parsers-formatters">10、关于解析器和格式化</a><br><a href="#work-progress">11、正在进行中的工作</a></p>
<p><img src="http://www.yearofmoo.com/images/site/mookins/20.png" alt="盗图2"></p>
<h2 id="Angular中的表单验证"><a href="#Angular中的表单验证" class="headerlink" title="Angular中的表单验证"></a><span id="angular-form">Angular中的表单验证</span></h2><p>表单验证在任何一个框架中都是一只晋安驯服的野兽。在Vanilla JS中就更加让人捉摸不透。虽然已经有一些在制定中的HTML5表单验证API，但是这些API是不一致的，同时不失所有设备都很好的支持，甚至一些平台根本就不支持它们。</p>
<p>幸亏AngularJs通过ngModel对表单验证做了一个多功能的包装。如果需要的话ngModel的内部验证也可以只使用HTML5验证API，当然ngModel总体上的跨浏览器的统一性还是非常不错的。AngularJs 1.3对表单的控制能力远远高于1.2版本。</p>
<p>不过还有好多知识点需要理解的，让我们快点开始吧……</p>
<h2 id="演讲视频，Github仓库和演示应用"><a href="#演讲视频，Github仓库和演示应用" class="headerlink" title="演讲视频，Github仓库和演示应用"></a><span id="video-github">演讲视频，Github仓库和演示应用</span></h2><p>不是很久以前，那是在2014年6月多伦多的AngularJs交流会上，我讲述了AngularJs的表单验证，几乎涵盖了这篇文章的所有话题。视频放在Youtube上，链接在下面。<strong>请记住在当时，异步验证API还不稳定</strong>。所以当视频中讨论API对于基于promise的验证是如何工作的时候，请查看一下本文章的后面部分。除此，好好欣赏视频吧，期望你能喜欢我潇洒的幽默。</p>
<p>视频传送门[Youtube视频，要爬长城才能看到的额]：<a href="https://www.youtube.com/watch?v=AgdGhZvzUxg&amp;feature=youtu.be" target="_blank" rel="external">AngularJs - ngModel Form Validation</a></p>
<p>有一个朋友的示范仓库展示了本文列出的所有特性，在线示范和仓库地址如下：<br><a href="http://yom.nu/ng-forms-demo" target="_blank" rel="external">查看示范应用</a><br><a href="http://yom.nu/ng-forms-code" target="_blank" rel="external">查看Github仓库</a></p>
<h2 id="基础知识"><a href="#基础知识" class="headerlink" title="基础知识"></a><span id="basics">基础知识</span></h2><p>我们不能假想所有的人都了解Angular的表单是如何使用的，所以在开始之前先简要的介绍一下如何使用。</p>
<h3 id="使用ngModel收集数据"><a href="#使用ngModel收集数据" class="headerlink" title="使用ngModel收集数据"></a>使用ngModel收集数据</h3><p>用户angular的人就会知道，ng-model属性总是位于输入元素上，如（input, select, textarea）。这个强大的指令连接中DOM种输入元素的输入值（称为“view value”）和对应作用域（scope）中的数据模型值（称为“model value”）,即当用户输入时，输入值（view value）改变，对应的数据模型值（model value）也会相应更新，反之亦然。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"field"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">ng-model</span>=<span class="string">"myName"</span> /&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span>My name is <span class="tag">&lt;<span class="name">strong</span>&gt;</span><span class="tag">&lt;/<span class="name">strong</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">ng-click</span>=<span class="string">"myName='default value'"</span>&gt;</span>Reset to 'default value'<span class="tag">&lt;/<span class="name">button</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div></pre></td></tr></table></figure>
<p>现在当用户再input元素上输入值的时候，scope中的对应数据模型会同步此值。当按钮被按下的时候，scope中的myName属性值会变化，然后input输入域会显示这个值（‘defaut value’）。</p>
<h3 id="数据模型值和控制器"><a href="#数据模型值和控制器" class="headerlink" title="数据模型值和控制器"></a>数据模型值和控制器</h3><p>控制值在DOM（view value）和scope（model value）中传递的逻辑是由ngModelController提供的。每当一个输入元素有ng-model属性时，ngModel指令会创建一个ngModelController的实例来处理所有的值的解析，格式化和传递。</p>
<p>这种机制的好处是我们不用写任何js代码就可以完成一些标准的处理流程，如传递数据给scope，执行验证器，触发数据模型绑定的事件。看一下下面的代码：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"field"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"email"</span></span></div><div class="line">        <span class="attr">minlength</span>=<span class="string">"5"</span></div><div class="line">        <span class="attr">maxlength</span>=<span class="string">"100"</span></div><div class="line">        <span class="attr">ng-model</span>=<span class="string">"myEmail"</span></div><div class="line">        <span class="attr">required</span> /&gt;</div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div></pre></td></tr></table></figure>
<p>上面的input元素通过ng-model指令绑定了一个scope中的myEmail属性。用户输入数据时将自动修改scope上的myEmail属性值为输入值。同时input元素上还定义了一系列的验证器来验证用户的输入，只有当用户输入的值满足所有定义验证器的条件，这个输入值才会被angualr写入到scope中绑定的属性上。上面例子中，ngModelController将会检查：</p>
<pre><code>* 输入值不能为空（required）
* 输入值最小长度为5（minlength）
* 输入值最大长度为100（maxlength）
* 输入值须是一个合法的邮箱地址（type=&quot;email&quot;）
</code></pre><p>通过这四个验证器我们不用写一行js代码就可完成表单验证，同时可以在不同的表单元素上复用。</p>
<p>当一个验证器验证失败的时候，将会把错误信息注册到ngModelController实例中的$error对象中。不过要想展示错误信息的话，我们首先需要能在模板（html）中访问这个ngModelController 的model，此处可以把输入元素用一个form元素包裹，同时给form元素和input元素写上自己的name属性和值。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">name</span>=<span class="string">"myForm"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"field"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"email"</span></span></div><div class="line">            <span class="attr">name</span>=<span class="string">"myEmail"</span></div><div class="line">            <span class="attr">minlength</span>=<span class="string">"5"</span></div><div class="line">            <span class="attr">maxlength</span>=<span class="string">"100"</span></div><div class="line">            <span class="attr">ng-model</span>=<span class="string">"myEmail"</span></div><div class="line">            <span class="attr">required</span> /&gt;</div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></div></pre></td></tr></table></figure>
<p>现在我们可以在模板中通过myForm.myEmail.$error检查此input元素的验证状态，同时还可以检查表单元素的其他状态属性，如$pristine(未被修改过为true), $dirty(修改过为true), $valid(通过验证), $invalid（未通过验证）。通过这些值我们可以在模板中定义何时显示错误信息。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">name</span>=<span class="string">"myForm"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"field"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"email"</span></span></div><div class="line">            <span class="attr">name</span>=<span class="string">"myEmail"</span></div><div class="line">            <span class="attr">minlength</span>=<span class="string">"5"</span></div><div class="line">            <span class="attr">maxlength</span>=<span class="string">"100"</span></div><div class="line">            <span class="attr">ng-model</span>=<span class="string">"myEmail"</span></div><div class="line">            <span class="attr">required</span> /&gt;</div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"myForm.myEmail.$invalid"</span>&gt;</span>There is an error with the field...<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></div></pre></td></tr></table></figure>
<p>我们可以创建自定义的ngModel组件指令来访问ngModelController实例并实现验证器，所有要做的仅仅是在指令定义时通过require属性来注入ngModel的控制器。这种方式创建的指令需要和ngModel一起使用。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//</span></div><div class="line"><span class="comment">// Use this in your templates like so</span></div><div class="line"><span class="comment">// &lt;input type="text" custom-validator ng-model="myModel" /&gt;</span></div><div class="line"><span class="comment">//</span></div><div class="line">ngModule.directive(<span class="string">'customValidator'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</div><div class="line">    <span class="built_in">require</span> : <span class="string">'ngModel'</span>,</div><div class="line">    <span class="attr">link</span> : <span class="function"><span class="keyword">function</span>(<span class="params">scope, element, attrs, ngModel</span>) </span>&#123;</div><div class="line">        ngModel.$validators.myValidator = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; ... &#125;</div><div class="line">    &#125; </div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>form元素拥有自己的控制器，form的控制器是为了管理整个表单验证而添加的，它拥有$valid和$invalid属性。下面的例子是一个根据表单是否通过验证的状态来决定是否把数据提交到后台的表单控制器。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">ngModule.controller(<span class="string">'FormCtrl'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">$http</span>) </span>&#123;</div><div class="line">    <span class="keyword">this</span>.submit = <span class="function"><span class="keyword">function</span>(<span class="params">isValid, data</span>) </span>&#123;</div><div class="line">        <span class="keyword">if</span>(!isValid) <span class="keyword">return</span>;</div><div class="line"></div><div class="line">        <span class="comment">//submit the data to the server</span></div><div class="line">        $http.post(<span class="string">'/api/submit'</span>, data);</div><div class="line">    &#125;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>在form的html模板中通过ng-submit属性指定表单提交时调用控制器中的submit方法。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">ng-controller</span>=<span class="string">"FormCtrl as form"</span></span></div><div class="line">    <span class="attr">name</span>=<span class="string">"myForm"</span> </div><div class="line">    <span class="attr">ng-submit</span>=<span class="string">"form.submit(myForm.$valid, data)"</span>&gt;</div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"field"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"email"</span></span></div><div class="line">            <span class="attr">name</span>=<span class="string">"myEmail"</span></div><div class="line">            <span class="attr">minlength</span>=<span class="string">"5"</span></div><div class="line">            <span class="attr">maxlength</span>=<span class="string">"100"</span></div><div class="line">            <span class="attr">ng-model</span>=<span class="string">"data.myEmail"</span></div><div class="line">            <span class="attr">required</span> /&gt;</div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"myForm.myEmail.$invalid"</span>&gt;</span>There is an error with the field<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></div></pre></td></tr></table></figure>
<p>不知你是否注意都我们使用了一个data集合来存储所有的表单数据模型。如果我们仅仅且把所有的表单数据模型存储在一个集合中，那么在提交表单时可以直接把这个集合提交给后台。这种模式为我们省去不少的js代码。</p>
<p>希望上面的介绍是你初略的了解了ngModel的一些基本知识。接下来我们开始介绍AngualrJs 1.3中的那些新特性。</p>
<h2 id="HTML5验证器和解析错误"><a href="#HTML5验证器和解析错误" class="headerlink" title="HTML5验证器和解析错误"></a><span id="html5-validation-errors">HTML5验证器和解析错误</span></h2><p>现在所有的HTMl5验证器都被绑定到ngModel上，当错误发生时，错误信息将作为属性挂在ngModel.$error上。下面的表格展示了属性名和错误错误类型的对应关系。</p>
<table>
<thead>
<tr>
<th style="text-align:center">HTML5 Attribute</th>
<th style="text-align:center">ng Attribute</th>
<th style="text-align:center">Registered Error</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">required=”bool”</td>
<td style="text-align:center">ng-required=”…”</td>
<td style="text-align:center">ngModel.$error.required</td>
</tr>
<tr>
<td style="text-align:center">minlength=”number”</td>
<td style="text-align:center">ng-minlength=”number”</td>
<td style="text-align:center">ngModel.$error.minlength</td>
</tr>
<tr>
<td style="text-align:center">maxlength=”number”</td>
<td style="text-align:center">ng-maxlength=”number”</td>
<td style="text-align:center">ngModel.$error.maxlength</td>
</tr>
<tr>
<td style="text-align:center">min=”number”</td>
<td style="text-align:center">ng-min=”number”</td>
<td style="text-align:center">ngModel.$error.min</td>
</tr>
<tr>
<td style="text-align:center">max=”number”</td>
<td style="text-align:center">ng-max=”number”</td>
<td style="text-align:center">ngModel.$error.max</td>
</tr>
<tr>
<td style="text-align:center">pattern=”patternValue”</td>
<td style="text-align:center">ng-pattern=”patternValue”</td>
<td style="text-align:center">ngModel.$error.pattern</td>
</tr>
</tbody>
</table>
<p>下面的input元素的type类型也会注册验证器。</p>
<table>
<thead>
<tr>
<th style="text-align:center">&lt;input type=”…”&gt;</th>
<th style="text-align:center">Registered Error</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">type=”email”</td>
<td style="text-align:center">ngModel.$error.email</td>
</tr>
<tr>
<td style="text-align:center">type=”url”</td>
<td style="text-align:center">ngModel.$error.url</td>
</tr>
<tr>
<td style="text-align:center">type=”number”</td>
<td style="text-align:center">ngModel.$error.number</td>
</tr>
<tr>
<td style="text-align:center">type=”date”</td>
<td style="text-align:center">ngModel.$error.date</td>
</tr>
<tr>
<td style="text-align:center">type=”time”</td>
<td style="text-align:center">ngModel.$error.time</td>
</tr>
<tr>
<td style="text-align:center">type=”datetime-local”</td>
<td style="text-align:center">ngModel.$error.datetimelocal</td>
</tr>
<tr>
<td style="text-align:center">type=”week”</td>
<td style="text-align:center">ngModel.$error.week</td>
</tr>
<tr>
<td style="text-align:center">type=”month”</td>
<td style="text-align:center">ngModel.$error.month</td>
</tr>
</tbody>
</table>
<h3 id="ngModel如何处理这些错误"><a href="#ngModel如何处理这些错误" class="headerlink" title="ngModel如何处理这些错误"></a>ngModel如何处理这些错误</h3><p>由于HTML5自身带有的表单验证特性，一些类型的input输入框只有当输入值满足验证条件后才会生效（也就是element.value只能取到通过验证的输入值）。</p>
<p>在1.3中，ngModel将先处理解析相关的验证，然后才是其它的验证。也就是说会先判断一个值是否是符合number, date, url和email这种类型验证，然后才是其它的如required, minlength, max等等。</p>
<p><a href="http://plnkr.co/edit/UuF2H1poVvPfiePEhDif?p=preview" target="_blank" rel="external">一个小小Demo</a></p>
<h2 id="验证器管道-validators-pipeline"><a href="#验证器管道-validators-pipeline" class="headerlink" title="验证器管道($validators pipeline)"></a><span id="validators-pipeline">验证器管道($validators pipeline)</span></h2><p>在AngularJs 1.3中我们使用$validators来代替以前的$parsers和$formatters实现表单验证。为了将自定义验证器注册到表单验证器中（ngModel.$validators），我们需要先创建包含ngModel的自定义指令。下面的例子展示了如何通过$validators定义一个判断密码输入是否符合要求的验证器。</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line">ngModule.directive('validatePasswordCharacters', function() &#123;</div><div class="line">    // /\d+/,       //numeric values</div><div class="line">    // /[a-z]+/     //lowercase values</div><div class="line">    // /[A-Z]+/     //uppercase values</div><div class="line">    // /\W+/        //special characters</div><div class="line">    // /^\S+$/      //no whitespace allowed</div><div class="line">    var REQUIRED_PATTERNS = [</div><div class="line">        /\d+/,</div><div class="line">        /[a-z]+/,</div><div class="line">        /[A-Z]+/,</div><div class="line">        /\W+/,</div><div class="line">        /^\S+$/</div><div class="line">    ];</div><div class="line"></div><div class="line">    return &#123;</div><div class="line">        require : 'ngModel',</div><div class="line">        link : function($scope, element, attrs, ngModel) &#123;  </div><div class="line">            ngModel.$validators.passwordCharacters = function(value) &#123;</div><div class="line">                var status = true;</div><div class="line">                angular.forEach(REQUIRED_PATTERNS, function(pattern) &#123;</div><div class="line">                    status = status &amp;&amp; pattern.test(value);</div><div class="line">                &#125;);</div><div class="line">                return status;</div><div class="line">            &#125;; </div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>当在控制器管道（给$validators添加属性）注册验证器时需要函数返回一个布尔类型的值。</p>
<p>对应的HTML代码如下</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">name</span>=<span class="string">"myForm"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"label"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">name</span>=<span class="string">"myPassword"</span> <span class="attr">type</span>=<span class="string">"password"</span> <span class="attr">ng-model</span>=<span class="string">"data.password"</span> <span class="attr">validate-password-characters</span> <span class="attr">required</span> /&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"myForm.myPassword.$error.required"</span>&gt;</span></div><div class="line">          You did not enter a password</div><div class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"myForm.myPassword.$error.passwordCharacters"</span>&gt;</span></div><div class="line">          Your password must contain a numeric, uppercase and lowercase as well as special characters</div><div class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></div></pre></td></tr></table></figure>
<h2 id="通过异步验证器实现异步验证"><a href="#通过异步验证器实现异步验证" class="headerlink" title="通过异步验证器实现异步验证"></a><span id="async-validators">通过异步验证器实现异步验证</span></h2><p>下面让我们用同样的方式来创建一异步验证器功能的指令，通过ajax与后台交互的结果来判断输入的用户名是否可用。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">ngModule.directive(<span class="string">'usernameAvailableValidator'</span>, [<span class="string">'$http'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">$http</span>) </span>&#123;</div><div class="line">    <span class="keyword">return</span> &#123;</div><div class="line">        <span class="attr">require</span> : <span class="string">'ngModel'</span>,</div><div class="line">        <span class="attr">link</span> : <span class="function"><span class="keyword">function</span>(<span class="params">$scope, element, attrs, ngModel</span>) </span>&#123;</div><div class="line">            ngModel.$asyncValidators.usernameAvailable = <span class="function"><span class="keyword">function</span>(<span class="params">username</span>) </span>&#123;</div><div class="line">                <span class="keyword">return</span> $http.get(<span class="string">'/api/username-exists?u='</span>+ username);</div><div class="line">            &#125;;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;]);</div></pre></td></tr></table></figure>
<p>异步验证器($asyncValidators)在触发的时候需要每个验证器返回一个promise对象。当这个promise完成的时候表示验证通过，拒绝（reject）的时候将把验证的错误信息注册到对应的$error对象上。只有当所有的验证器（包含异步验证器）验证通过后，值才会被写入scope中。</p>
<p>需要记住的是，异步验证器只有再其他验证器全部验证通过后才会触发。这种机制有效的防止了在用户名无效时发送无意义的后端验证请求。下面的样例代码很好的诠释了这点。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">name</span>=<span class="string">"myForm"</span>&gt;</span></div><div class="line">    <span class="comment">&lt;!-- </span></div><div class="line">      first the required, pattern and minlength validators are executed</div><div class="line">      and then the asynchronous username validator is triggered...</div><div class="line">    --&gt;</div><div class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span></span></div><div class="line">        <span class="attr">class</span>=<span class="string">"input"</span></div><div class="line">        <span class="attr">name</span>=<span class="string">"username"</span></div><div class="line">        <span class="attr">minlength</span>=<span class="string">"4"</span></div><div class="line">        <span class="attr">maxlength</span>=<span class="string">"15"</span></div><div class="line">        <span class="attr">ng-model</span>=<span class="string">"form.data.username"</span></div><div class="line">        <span class="attr">pattern</span>=<span class="string">"^[-\w]+$"</span></div><div class="line">        <span class="attr">username-available-validator</span></div><div class="line">        <span class="attr">placeholder</span>=<span class="string">"Choose a username for yourself"</span></div><div class="line">        <span class="attr">required</span> /&gt;</div><div class="line">    <span class="comment">&lt;!-- ... --&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></div></pre></td></tr></table></figure>
<h3 id="异步验证期间的-valid和-invalid"><a href="#异步验证期间的-valid和-invalid" class="headerlink" title="异步验证期间的$valid和$invalid"></a>异步验证期间的$valid和$invalid</h3><p>当一个或多个异步验证器正在验证中时，对应model和form的$valid和$invalid标志都被置为undefined，只有当所有的异步验证器完成后，$valid和$invalid才会根据所有验证器验证的结果来赋值(true or false)。在这个期间，在modal和form上会有一个特殊的标志$pending(值为true)来标识，当所有异步验证完成后这个值将被移除。</p>
<h3 id="展示加载中动画"><a href="#展示加载中动画" class="headerlink" title="展示加载中动画"></a>展示加载中动画</h3><p>因此，通过$pending标志我们可以在正在执行异步验证的input旁边加上“加载中动画”，正如上面的用户名的异步验证，可以修改如下。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">name</span>=<span class="string">"myForm"</span>&gt;</span></div><div class="line">    <span class="comment">&lt;!-- first the required, pattern and minlength validators are executed</span></div><div class="line">       and then the asynchronous username validator is triggered --&gt;</div><div class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span></span></div><div class="line">        <span class="attr">name</span>=<span class="string">"myUsername"</span></div><div class="line">        <span class="attr">ng-model</span>=<span class="string">"data.username"</span></div><div class="line">        <span class="attr">minlength</span>=<span class="string">"10"</span></div><div class="line">        <span class="attr">pattern</span>=<span class="string">"^[-\w]+$"</span></div><div class="line">        <span class="attr">validate-username-availability</span></div><div class="line">        <span class="attr">required</span> /&gt;</div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"myForm.myUsername.$pending"</span>&gt;</span></div><div class="line">        Checking Username...</div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></div></pre></td></tr></table></figure>
<h2 id="错误消息渲染"><a href="#错误消息渲染" class="headerlink" title="错误消息渲染"></a><span id="errors-rendering">错误消息渲染</span></h2><p>Angular会默认展示模板中定义的所有错误提示，我们有很多方式来优化这种提示。</p>
<h3 id="使用ngIf或者ngShow-ngHide"><a href="#使用ngIf或者ngShow-ngHide" class="headerlink" title="使用ngIf或者ngShow/ngHide"></a>使用ngIf或者ngShow/ngHide</h3><p>一个input输入域在聚焦(focus)再失去焦点(blur)后，它的$touched属性都会是true。所以我们可以使用ngIf或者ngShow指令根据$touched的值来控制错误信息何时显示。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">name</span>=<span class="string">"myForm"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"colorCode"</span> <span class="attr">ng-model</span>=<span class="string">"data.colorCode"</span> <span class="attr">minlength</span>=<span class="string">"6"</span> <span class="attr">required</span> /&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"myForm.colorCode.$touched"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"myForm.colorCode.$error.required"</span>&gt;</span>...<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"myForm.colorCode.$error.minlength"</span>&gt;</span>...<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"myForm.colorCode.$error.pattern"</span>&gt;</span>...<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">nav</span> <span class="attr">class</span>=<span class="string">"actions"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"submit"</span> /&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">nav</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></div></pre></td></tr></table></figure>
<p>但是思考一下如果我们没有聚焦到任何一个输入域就直接提交表单呢，是不是也应该展示所有错误信息？我们可以增加一个对myForm.$submitted属性的判断来修复这个bug。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">name</span>=<span class="string">"myForm"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"colorCode"</span> <span class="attr">ng-model</span>=<span class="string">"data.colorCode"</span> <span class="attr">minlength</span>=<span class="string">"6"</span> <span class="attr">required</span> /&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"myForm.$submitted || myForm.colorCode.$touched"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"myForm.colorCode.$error.required"</span>&gt;</span>...<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"myForm.colorCode.$error.minlength"</span>&gt;</span>...<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"myForm.colorCode.$error.pattern"</span>&gt;</span>...<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">nav</span> <span class="attr">class</span>=<span class="string">"actions"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"submit"</span> /&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">nav</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></div></pre></td></tr></table></figure>
<p>现在这个表单就变得更加友好了。但是当错误信息太多了回发生什么？我们应该如何控制错误信息展示的时机和行为？如何给这些错误提示给一个优先级使得每次只显示一条错误提示？AngularJs 1.3通过一个新的ngMessages模块提供了这些功能。</p>
<h3 id="使用ngMessages"><a href="#使用ngMessages" class="headerlink" title="使用ngMessages"></a>使用ngMessages</h3><p>下面使用ngMessages来显示错误信息。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">name</span>=<span class="string">"myForm"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"colorCode"</span> <span class="attr">ng-model</span>=<span class="string">"data.colorCode"</span> <span class="attr">minlength</span>=<span class="string">"6"</span> <span class="attr">required</span> /&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-messages</span>=<span class="string">"myForm.colorCode.$error"</span> <span class="attr">ng-if</span>=<span class="string">"myForm.$submitted || myForm.colorCode.$touched"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-message</span>=<span class="string">"required"</span>&gt;</span>...<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-message</span>=<span class="string">"minlength"</span>&gt;</span>...<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-message</span>=<span class="string">"pattern"</span>&gt;</span>...<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">nav</span> <span class="attr">class</span>=<span class="string">"actions"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"submit"</span> /&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">nav</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></div></pre></td></tr></table></figure>
<p>使用ng-messages最多只会有一条错误信息会被展示。并且ng-messages指令会按照html模板中的顺序渲染第一条匹配的错误提示。注意到此处我们仍然使用了前面的ng-if属性来控制错误信息块是否显示。</p>
<p>为了能够再项目中使用ngMessage，我们需要下载并引入angular-messages.js文件，并将它作为我们应用的一个依赖注入。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span> <span class="attr">src</span>=<span class="string">"angular-messages.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span><span class="javascript"></span></div><div class="line">    <span class="keyword">var</span> ngModule = angular.module(<span class="string">'myApp'</span>, [<span class="string">'ngMessages'</span>]);</div><div class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div></pre></td></tr></table></figure>
<p>扩展阅读：<a href="http://www.yearofmoo.com/2014/05/how-to-use-ngmessages-in-angularjs.html" target="_blank" rel="external">ngMessage详解</a></p>
<h2 id="控制何时更新数据模型-model"><a href="#控制何时更新数据模型-model" class="headerlink" title="控制何时更新数据模型(model)"></a><span id="ng-model-options">控制何时更新数据模型(model)</span></h2><p>AngularJs 1.3中添加了一个新的ngModelOptions属性，通过对该属性的配置可以控制input元素上的ngModel何时更新。一个典型的应用就是防止值抖动(value debouncing)。通过这个属性可以让数据模型值(model value)只有在特定事件发生时才更新。以往默认的行为是每次字符输入都会更新数据模型值。</p>
<p>下面的例子展示的是只有在用户停止输入500毫秒后(500ms内不得再输入，否则重新计时)才出发绑定的所有验证器。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span></span></div><div class="line">    <span class="attr">name</span>=<span class="string">"myUsername"</span></div><div class="line">    <span class="attr">ng-model</span>=<span class="string">"data.username"</span></div><div class="line">    <span class="attr">minlength</span>=<span class="string">"10"</span></div><div class="line">    <span class="attr">pattern</span>=<span class="string">"^[-\w]+$"</span></div><div class="line">    <span class="attr">validate-username-availability</span></div><div class="line">    <span class="attr">ng-model-options</span>=<span class="string">"&#123; debounce : &#123; 'default' : 500 &#125; &#125;"</span></div><div class="line">    <span class="attr">required</span> /&gt;</div></pre></td></tr></table></figure>
<p>同时可以通过设置blur属性值为0使得当输入域失去焦点时立即触发验证。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">ng-model-options="&#123; debounce : &#123; 'default' : 500, blur : 0 &#125; &#125;"</div></pre></td></tr></table></figure>
<p>另一个应用场景是根据用户输入的搜索字符串来改变当前页面的url地址的时候，可以观看前面的视频作详细了解。</p>
<h2 id="动态生成表单元素"><a href="#动态生成表单元素" class="headerlink" title="动态生成表单元素"></a><span id="dynamic-forms">动态生成表单元素</span></h2><p>引入ng-if是因为它能很容易的添加和移除form的子区域。如此可以很好地控制表单中可选区域的添加和移除。想象一下如何编写一个只有在用户想要提供邮箱地址时候才展示邮箱收集输入框的form表单。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">form</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"field"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">label</span>&gt;</span></div><div class="line">            <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"checkbox"</span> <span class="attr">ng-model</span>=<span class="string">"data.allowNotifications"</span> /&gt;</span></div><div class="line">            Notify me via email 30 minutes before my event happens</div><div class="line">        <span class="tag">&lt;/<span class="name">label</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"field"</span> <span class="attr">ng-if</span>=<span class="string">"data.allowNotifications"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">label</span>&gt;</span>Notification Email:<span class="tag">&lt;/<span class="name">label</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"email"</span> <span class="attr">ng-model</span>=<span class="string">"data.notificationEmail"</span> <span class="attr">name</span>=<span class="string">"notificationEmail"</span> <span class="attr">required</span> /&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"></div><div class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"submit"</span> /&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></div></pre></td></tr></table></figure>
<p>上面代码的核心点就是邮箱输入框只会在checkbox为true时候被添加。由于这个输入域是根据状态添加到DOM中和从DOM中移除的，所以它的添加和移除会直接影响到整个form的验证状态。</p>
<h3 id="嵌套重复的表格"><a href="#嵌套重复的表格" class="headerlink" title="嵌套重复的表格"></a>嵌套重复的表格</h3><p>如果我们现在需要不止一个邮箱输入框，那么我们该如何重构我们的HTML代码呢(保证表单的验证和错误提示方式与前面一致，每个输入域【input】和form都有自己的提示和验证)？我们可以使用ng-repeat指令生成需要的输入域并绑定数据模型。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"field"</span> <span class="attr">ng-if</span>=<span class="string">"data.allowNotifications"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-repeat</span>=<span class="string">"email in notifcationEmails"</span>&gt;</span> </div><div class="line">        <span class="tag">&lt;<span class="name">label</span>&gt;</span>Email :<span class="tag">&lt;/<span class="name">label</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"email"</span> <span class="attr">ng-model</span>=<span class="string">"email"</span> <span class="attr">name</span>=<span class="string">"notificationEmail"</span> /&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div></pre></td></tr></table></figure>
<p>上面的代码当某一个邮箱输入错误时会发生什么呢？我们如何知道是哪一个输入框错误呢？如何给错误的输入框给出单独的错误提示呢？解决方法是使用ng-form指令给重复元素创建嵌套的表单域。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"field"</span> <span class="attr">ng-if</span>=<span class="string">"data.allowNotifications"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-form</span>=<span class="string">"emailForm"</span> <span class="attr">ng-repeat</span>=<span class="string">"email in notifcationEmails"</span>&gt;</span> </div><div class="line">        <span class="tag">&lt;<span class="name">label</span>&gt;</span>Email :<span class="tag">&lt;/<span class="name">label</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"email"</span> <span class="attr">ng-model</span>=<span class="string">"email"</span> <span class="attr">name</span>=<span class="string">"notificationEmail"</span> /&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"emailForm.notificationEmail.$error.email"</span>&gt;</span></div><div class="line">            You did not enter a valid email address</div><div class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"></div><div class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">ng-click</span>=<span class="string">"addAnotherEmail()"</span>&gt;</span>Add another email<span class="tag">&lt;/<span class="name">button</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div></pre></td></tr></table></figure>
<p>牛逼啊！等等…这满屏的错误提示你玩我呢？我只想对循环生成的同类型的邮箱地址验证给出一个总的提示就够了！绝对事儿逼啊…满足你，我们再在循环块的包含块上增加一个ng-form指令就行啦…233…就是这么叼…</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"field"</span> <span class="attr">ng-if</span>=<span class="string">"data.allowNotifications"</span> <span class="attr">ng-form</span>=<span class="string">"notificationEmails"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-form</span>=<span class="string">"emailForm"</span> <span class="attr">ng-repeat</span>=<span class="string">"email in notifcationEmails"</span>&gt;</span> </div><div class="line">        <span class="tag">&lt;<span class="name">label</span>&gt;</span>Email :<span class="tag">&lt;/<span class="name">label</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"email"</span> <span class="attr">ng-model</span>=<span class="string">"email"</span> <span class="attr">name</span>=<span class="string">"notificationEmail"</span> /&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"emailForm.notificationEmail.$error.email"</span>&gt;</span></div><div class="line">            You did not enter a valid email address</div><div class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">ng-if</span>=<span class="string">"notificationEmails.$error.email"</span> <span class="attr">class</span>=<span class="string">"error"</span>&gt;</span></div><div class="line">        One or more emails have been incorrectly entered.</div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"></div><div class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">ng-click</span>=<span class="string">"addAnotherEmail()"</span>&gt;</span>Add another email<span class="tag">&lt;/<span class="name">button</span>&gt;</span></div><div class="line"></div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div></pre></td></tr></table></figure>
<h2 id="关于解析器和格式化"><a href="#关于解析器和格式化" class="headerlink" title="关于解析器和格式化"></a><span id="parsers-formatters">关于解析器和格式化</span></h2><p>ngModelController的解析器($parsers)和格式化($formatters)在1.3中没有任何改变，但是她们将不再应该用于处理验证逻辑。$parsers应该用于将显示值(view value)解析成一个不同数据模型值(model value)，$formatters则用于将模型值(model value)格式化成合适的显示值(view model)。有必要再次强调一个概念——模型值(model value)表示存储在scope中的值，而显示值(view value)是指存在于DOM中input元素上的值。</p>
<p>一个好的使用例子是用于处理时间相关的输入元素，如date, time, datetime, week, month等等。下面的实例中的显示值是一个字符串，而对应的模型值却是一个Date实例。来来来，上代码。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> DATE_REGEXP = <span class="regexp">/^(\d&#123;4&#125;)-(\d&#123;2&#125;)-(\d&#123;2&#125;)$/</span>;</div><div class="line"></div><div class="line"><span class="comment">//grab ngModel inside of a directive</span></div><div class="line">ngModel.$parsers.push(<span class="function"><span class="keyword">function</span>(<span class="params">value</span>) </span>&#123;</div><div class="line">    <span class="keyword">if</span> (value == <span class="string">''</span> || value == <span class="literal">null</span> || value == <span class="literal">undefined</span>) &#123;</div><div class="line">        <span class="comment">// null means that there is no value which is fine</span></div><div class="line">        <span class="keyword">return</span> <span class="literal">null</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">if</span> (DATE_REGEXP.test(value)) &#123;</div><div class="line">        <span class="keyword">return</span> parseDateFromString(value);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// undefined means that the date syntax is invalid and</span></div><div class="line">    <span class="comment">// this will cause a parse error during validation</span></div><div class="line">    <span class="keyword">return</span> <span class="literal">undefined</span>;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>$formatters是$parsers的逆过程。所以我们需要向下面这样把一个Date实例的模型值格式化成对应的字符串展示。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//grab ngModel inside of a directive</span></div><div class="line">ngModel.$formatters.push(<span class="function"><span class="keyword">function</span>(<span class="params">value</span>) </span>&#123;</div><div class="line">    <span class="keyword">if</span>(angular.isDate(value)) &#123;</div><div class="line">        value = $filter(<span class="string">'date'</span>)(value, [<span class="string">'yyyy'</span>, <span class="string">'MM'</span>, <span class="string">'dd'</span>]);</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="keyword">return</span> value;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>因此$parsers和$formatters总是成对工作的，只有这样才能使得值在两种不同的类型或者要求下正确转换。</p>
<h2 id="正在进行中的工作"><a href="#正在进行中的工作" class="headerlink" title="正在进行中的工作"></a><span id="work-progress">正在进行中的工作</span></h2><p>ngModel在AngularJs最初版本就已经存在，到现在1.3版本中的新特性极大的提升了开发者和使用者的体验。虽然现在新特性可能还有一两处不恰当的地方，但这些不足将在1.3的稳定版本中被修改。但现在你可以放心大胆的用RC0发布版中的新特性，因为所有API已经冻结，不会再做修改。所以勇敢向前吧，骚年…不要害羞:)</p>
<p>如果你发现有bug，或者有任何想法，欢迎到AngularJs的github仓库创建issue，记得在issue描述中@ matsko额。这样我才能能快速的看到您的反馈并响应。</p>
<p>非常感谢您阅读本篇文章。欢迎分享本文并在Twitter上关注<a href="https://twitter.com/yearofmoo" target="_blank" rel="external">@yearofmoo</a>。</p>
<hr>
<p>处女翻，欢迎轻拍。<br>译自：<a href="http://www.yearofmoo.com/2014/09/taming-forms-in-angularjs-1-3.html" target="_blank" rel="external">Taming Forms in AngularJS 1.3</a></p>
</span>
      
    </div>

    <footer class="post-footer">

      
        <div class="post-nav">
          <div class="post-nav-prev post-nav-item">
            
              <a href="/2015/12/06/penglu/checkbox-in-angularJs/" rel="prev">checkbox in angularJs</a>
            
          </div>

          <div class="post-nav-next post-nav-item">
            
              <a href="/2015/11/24/chenwubai/d3-basicCharts-radar/" rel="next">基于D3.js的雷达图的实现</a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>

 </div>

        

        
          <div class="comments" id="comments">
            <div id="SOHUCS" sid="" ></div>
          </div>
        
      </div>

      
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <a href="https://github.com/xgfe" target="_blank"><img class="site-author-image" src="http://p0.meituan.net/xgfe/082a9624ba5ae8602150a2d43968463e49348.png" alt="xgfe" itemprop="image"/></a>
          <p class="site-author-name" itemprop="name">xgfe</p>
        </div>
        <p class="site-description motion-element" itemprop="description">xgfe's blog. 鲜果前端的技术博客，鲜果前端研发部官方博客。前端基础技术研究：html, html5, javascript, css, css3；前端框架研究：angularJs, react, react native.</p>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">89</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          <div class="site-state-item site-state-categories">
            
              <span class="site-state-item-count">37</span>
              <span class="site-state-item-name">作者</span>
              
          </div>

          <div class="site-state-item site-state-tags">
            <a href="/tags">
              <span class="site-state-item-count">131</span>
              <span class="site-state-item-name">标签</span>
              </a>
          </div>

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" target="_blank" rel="alternate">
              <i class="menu-item-icon icon-next-feed"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/xgfe" target="_blank">GitHub</a>
              </span>
            
          
        </div>

        
        

        <div class="links-of-author motion-element">
          
        </div>

      </section>

      
        <section class="post-toc-wrap sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator"></div>
          <div class="post-toc">
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Angular中的表单验证"><span class="nav-number">1.</span> <span class="nav-text">Angular中的表单验证</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#演讲视频，Github仓库和演示应用"><span class="nav-number">2.</span> <span class="nav-text">演讲视频，Github仓库和演示应用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基础知识"><span class="nav-number">3.</span> <span class="nav-text">基础知识</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#使用ngModel收集数据"><span class="nav-number">3.1.</span> <span class="nav-text">使用ngModel收集数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据模型值和控制器"><span class="nav-number">3.2.</span> <span class="nav-text">数据模型值和控制器</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#HTML5验证器和解析错误"><span class="nav-number">4.</span> <span class="nav-text">HTML5验证器和解析错误</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#ngModel如何处理这些错误"><span class="nav-number">4.1.</span> <span class="nav-text">ngModel如何处理这些错误</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#验证器管道-validators-pipeline"><span class="nav-number">5.</span> <span class="nav-text">验证器管道($validators pipeline)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#通过异步验证器实现异步验证"><span class="nav-number">6.</span> <span class="nav-text">通过异步验证器实现异步验证</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#异步验证期间的-valid和-invalid"><span class="nav-number">6.1.</span> <span class="nav-text">异步验证期间的$valid和$invalid</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#展示加载中动画"><span class="nav-number">6.2.</span> <span class="nav-text">展示加载中动画</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#错误消息渲染"><span class="nav-number">7.</span> <span class="nav-text">错误消息渲染</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#使用ngIf或者ngShow-ngHide"><span class="nav-number">7.1.</span> <span class="nav-text">使用ngIf或者ngShow/ngHide</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用ngMessages"><span class="nav-number">7.2.</span> <span class="nav-text">使用ngMessages</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#控制何时更新数据模型-model"><span class="nav-number">8.</span> <span class="nav-text">控制何时更新数据模型(model)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#动态生成表单元素"><span class="nav-number">9.</span> <span class="nav-text">动态生成表单元素</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#嵌套重复的表格"><span class="nav-number">9.1.</span> <span class="nav-text">嵌套重复的表格</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#关于解析器和格式化"><span class="nav-number">10.</span> <span class="nav-text">关于解析器和格式化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#正在进行中的工作"><span class="nav-number">11.</span> <span class="nav-text">正在进行中的工作</span></a></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator"></div>
        </section>
      

    </div>
  </aside>


    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner"> <div class="copyright" >
  
  &copy; &nbsp; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="icon-next-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xgfe</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" target="_blank" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


 </div>
    </footer>

    <div class="back-to-top"></div>
  </div>

  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  
  
    <script type="text/javascript"> 
(function(){ 
var appid = 'cysWiXvkm'; 
var conf = 'prod_fc970dbe85103c7a79b2c4f3dc7fb190'; 
var width = window.innerWidth || document.documentElement.clientWidth; 
if (width < 960) { 
window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="http://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("http://changyan.sohu.com/upload/changyan.js",function(){window.changyan.api.config({appid:appid,conf:conf})}); } })(); </script>
    

  


  
  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>
  <script type="text/javascript" src="/js/fancy-box.js?v=0.4.5.1"></script>


  <script type="text/javascript" src="/js/helpers.js?v=0.4.5.1"></script>
  

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/js/motion_global.js?v=0.4.5.1" id="motion.global"></script>




  <script type="text/javascript" src="/js/nav-toggle.js?v=0.4.5.1"></script>
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  
<script type="text/javascript" src="/js/bootstrap.scrollspy.js?v=0.4.5.1" id="bootstrap.scrollspy.custom"></script>


<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 0.4 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    var $tocContent = $('.post-toc-content');
    if (isDesktop() && CONFIG.sidebar === 'post') {
      if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
        displaySidebar();
      }
    }
  });
</script>



  <script type="text/javascript">
    $(document).ready(function () {
      if (CONFIG.sidebar === 'always') {
        displaySidebar();
      }
      if (isMobile()) {
        FastClick.attach(document.body);
      }
    });
  </script>

  

  
  

  
  <script type="text/javascript" src="/js/lazyload.js"></script>
  <script type="text/javascript">
    $(function () {
      $("#posts").find('img').lazyload({
        placeholder: "/images/loading.gif",
        effect: "fadeIn"
      });
    });
  </script>

  <!-- google search, added by felix -->
  <script>
      $('#gg-form').on('submit', function(e) {
        var keyword = $.trim($(this).find('#gg-search-input').val());
        if (keyword) {
          location.href = 'https://www.google.com.hk/?gfe_rd=cr&ei=hXw8VpjtHuLC8AeSuIjQAg&gws_rd=ssl#safe=strict&q='+encodeURIComponent(keyword)+'+site:xgfe.github.io';
        }
        return false;
      });
  </script>
  <!-- baidu 站长自动推送 -->
  <script>
  (function(){
      var bp = document.createElement('script');
      bp.src = '//push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
  })();
  </script>
</body>
</html>
